package cn.xinfei.xdecision.data.core.frame.executors.collect;

import cn.xinfei.xdecision.common.model.datax.consts.VariableConst;
import cn.xinfei.xdecision.common.model.datax.exception.XDecisionDataException;
import cn.xinfei.xdecision.common.model.datax.exception.XDecisionDataExceptionType;
import cn.xinfei.xdecision.data.core.frame.executors.VarContext;
import cn.xinfei.xdecision.data.core.vo.VarCollectAwareVO;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class VarHandlerChain implements VarHandler {

    public final List<VarHandler> varHandlers = new ArrayList<>();

    public VarHandlerChain addHandler(VarHandler handler) {
        this.varHandlers.add(handler);
        return this;
    }

    @Override
    public void doHandle(VarContext context) {
        for (VarHandler varHandler : varHandlers) {
            if (context.isHandle()) {
                MDC.put(VariableConst.HANDLE_NAME, varHandler.getClass().getSimpleName());
                log.info("VarHandler =[{}] add to handle VarExecutor", varHandler.getClass().getSimpleName());
                long startTime = System.currentTimeMillis();
                try {
                    varHandler.doHandle(context);
                    long endTime = System.currentTimeMillis();
                    log.info("VarHandler =[{}] timeConsuming ={} MillSeconds",
                            varHandler.getClass().getSimpleName(),
                            endTime - startTime);
                } catch (Exception ex) {
                    log.error("VarHandler = [{}] fail cause = {}", varHandler.getClass().getSimpleName(), ex.getCause(), ex);
                    throw new XDecisionDataException(XDecisionDataExceptionType.DATA_HANDLER_EXECUTE_ERROR,
                            "VarHandler= " + varHandler.getClass().getSimpleName() + " 执行异常!");
                }
            } else {
                log.info("VarHandler =[{}] no variables to handle", varHandler.getClass().getSimpleName());
                break;
            }
        }
    }
}
